package com.yuyou.train.lesson.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.train.lesson.mapper.LessonClassMapper;
import com.yuyou.train.lesson.service.ILessonClassService;
import com.yuyou.train.lesson.service.ILessonClassUserRelationService;
import com.yuyou.train.lesson.service.ILessonResourceRuleRelationService;
import com.yuyou.train.lesson.service.ILessonService;
import com.yuyou.train.lesson.service.ILessonSubjectRelationService;
import com.yuyou.train.service.api.admin.service.AuthUserAPI;
import com.yuyou.train.service.api.lesson.dto.LessonClassDetailDTO;
import com.yuyou.train.service.api.lesson.dto.LessonClassPageDTO;
import com.yuyou.train.service.api.lesson.dto.LessonSubjectRelationDTO;
import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonClass;
import com.yuyou.train.service.api.lesson.entity.LessonClassUserRelation;
import com.yuyou.train.service.api.lesson.entity.LessonResourceRuleRelation;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.service.UserAPI;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.message.CommMess;
import com.yuyou.train.util.message.lesson.LessonClassMess;
import com.yuyou.train.util.message.user.UserMess;
import com.yuyou.train.util.tool.GenerateVerCodeUtils;
import com.yuyou.train.util.tool.Sequence;

@Service
public class LessonClassServiceImpl implements ILessonClassService{

	@Autowired
	private LessonClassMapper lessonClassMapper;
	@Autowired
	private ILessonClassUserRelationService classUseRelService;
	@Autowired
	private ILessonService lessonService;
	@Autowired
	private ILessonResourceRuleRelationService lesResRulRelService;
	
	@Autowired
	private UserAPI userAPI;
	
	@Autowired
	private AuthUserAPI authUserAPI;
	
	@Autowired
	private ILessonSubjectRelationService lesSubRelService;
	
	
	@Override
	public int deleteByPrimaryKey(String id) {
		return lessonClassMapper.deleteByPrimaryKey(id);
	}

	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<String> delLessonClass(String authUserId,String id) {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		//禁用状态下不能删除
		LessonClass lessonClass=this.selectByPrimaryKey(id);
		
		ResBoolSimpleInfo<String> areaRes=this.areaDataLimit(authUserId,lessonClass.getDataArea());
		if(!areaRes.isSuccess()){
			return new ResBoolSimpleInfo<String>(false,areaRes.getMessage());
		}
		
		if(lessonClass.getIsUse().equals(CommEnums.isUse.yes.getValue())){
			return new ResBoolSimpleInfo<String>(false,LessonClassMess.ERR_DEL_USE_NO);
		}
			
		//有课程不能删除
		List<Lesson> lessList=lessonService.findByClassId(id);
		if(lessList.size()>0){
			return new ResBoolSimpleInfo<String>(false,LessonClassMess.ERR_DEL_HAS_LESSON);
		}
		//有学员不能删除
		User user=new User();
		user.setClassId(id);
		List<User> list=userAPI.findUsers(user);
		if(list.size()>0){
			return new ResBoolSimpleInfo<String>(false,LessonClassMess.ERR_DEL_HAS_USER);
		}
		
		//删除班级
		lessonClassMapper.deleteByPrimaryKey(id);	
		//删除班级导师关系
		classUseRelService.deleteByClassIdAndType(id,UserEnums.type.teacher.getValue());

		res.setData(id);
		res.setSuccess(true);
		return res;
	}
	
	
	@Override
	public int insert(LessonClass record) {
		record.setId(Sequence.getSequence().getNextId());
		record.setIsUse(CommEnums.isUse.no.getValue());
		record.setCode(GenerateVerCodeUtils.generateVerCode(4));
		record.setCreateTime(new Date());
		return lessonClassMapper.insert(record);
	}

	@Override
	public LessonClass selectByPrimaryKey(String id) {
		return lessonClassMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(LessonClass record) {
		record.setUpdateTime(new Date());
		return lessonClassMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<LessonClass> addClass(String authUserId,LessonClass record, List<String> userIds) {
		ResBoolSimpleInfo<LessonClass> res=new ResBoolSimpleInfo<LessonClass>();
		
		List<String> teaList=new ArrayList<>();
		
			for(String userId:userIds){
				User u=userAPI.selectByUserId(userId);
				if(u.getIsFirst()==1 || u.getIsDel().equals(CommEnums.isDel.yes.getValue())){
					teaList.add(u.getUsername());
				}
			}	
			if(teaList.size()>0){
				String name=StringUtils.join(teaList, ",");
				res.setSuccess(false);
				res.setMessage(String.format(UserMess.ERR_NO_REGIS, name));
				return res;
			}
		
		
		ResBoolSimpleInfo<String> areaRes=this.areaDataLimit(authUserId,record.getDataArea());
		if(!areaRes.isSuccess()){
			res.setSuccess(false);
			res.setMessage(areaRes.getMessage());
			return res;
		}
		
		this.insert(record);
		for(String userId:userIds){
			LessonClassUserRelation re=new LessonClassUserRelation();
			re.setLessonClassId(record.getId());
			re.setUserId(userId);
			re.setType(UserEnums.type.teacher.getValue());
			classUseRelService.insert(re);
		}
		res.setSuccess(true);
		res.setData(record);
		return res;
	}

	
	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<LessonClass> updateClass(String authUserId,LessonClass record, List<String> userIds) {
		ResBoolSimpleInfo<LessonClass> res=new ResBoolSimpleInfo<LessonClass>();
				
		List<String> teaList=new ArrayList<>();
		if(userIds !=null){
			for(String userId:userIds){
				User u=userAPI.selectByUserId(userId);
				if(u.getIsFirst()==1 || u.getIsDel().equals(CommEnums.isDel.yes.getValue())){
					teaList.add(u.getUsername());
				}
			}	
			if(teaList.size()>0){
				String name=StringUtils.join(teaList, ",");
				res.setSuccess(false);
				res.setMessage(String.format(UserMess.ERR_NO_REGIS, name));
				return res;
			}
		}
		
		LessonClass lessonClass=this.selectByPrimaryKey(record.getId());
		ResBoolSimpleInfo<String> areaRes=this.areaDataLimit(authUserId,lessonClass.getDataArea());
		if(!areaRes.isSuccess()){
			res.setSuccess(false);
			res.setMessage(areaRes.getMessage());
			return res;
		}
		
		if(userIds !=null){
			classUseRelService.deleteByClassIdAndType(record.getId(),UserEnums.type.teacher.getValue());
			for(String userId:userIds){
				LessonClassUserRelation re=new LessonClassUserRelation();
				re.setLessonClassId(record.getId());
				re.setUserId(userId);
				re.setType(UserEnums.type.teacher.getValue());
				classUseRelService.insert(re);
			}
		}		
		this.updateByPrimaryKeySelective(record);
		res.setData(record);
		res.setSuccess(true);
		return res;
	}

	@Override
	public List<LessonClassPageDTO> findLessonClassPageList(
			Pagination<LessonClassPageDTO> p) {
		return lessonClassMapper.findLessonClassPageList(p);
	}

	@Override
	public int findLessonClassPageCount(Pagination<LessonClassPageDTO> p) {
		return lessonClassMapper.findLessonClassPageCount(p);
	}

	@Override
	public LessonClassDetailDTO selectDetail(String authUserId,String id,String type) {
		return lessonClassMapper.selectDetail(id,type);
	}

	@Override
	public LessonClass selectByCode(String code) {
		return lessonClassMapper.selectByCode(code);
	}


	@Override
	public List<LessonClass> findClass() {
		return lessonClassMapper.findClass();
	}

	@Override
	public ResBoolSimpleInfo<String> operateClass(String authUserId,String id, String isUse) {
		if(isUse.equals(CommEnums.isUse.yes.getValue())){
			List<Lesson> lessonList=lessonService.findByClassId(id);
			
			LessonClass lessonClass=this.selectByPrimaryKey(id);			
			ResBoolSimpleInfo<String> areaRes=this.areaDataLimit(authUserId,lessonClass.getDataArea());
			if(!areaRes.isSuccess()){
				return new ResBoolSimpleInfo<String>(false,areaRes.getMessage());
			}
			
			for(Lesson l:lessonList){
				//有课程没配置资源规则关系不能启动
				if(l.getIsLeaf().equals(CommEnums.isLeaf.yes.getValue())){
					LessonResourceRuleRelation rel=lesResRulRelService.selectByLessonId(l.getId());
					if(rel==null){
						return new ResBoolSimpleInfo<String>(false,String.format(LessonClassMess.ERR_USE_LESSON_REL_EMPTY, l.getName()));
					}
				}
				//没有配科目不能启动
				List<LessonSubjectRelationDTO> lesSubjectList=lesSubRelService.findBylessonId(l.getId());
				if(lesSubjectList.size()==0){
					return new ResBoolSimpleInfo<String>(false,String.format(LessonClassMess.ERR_USE_LESSON_SUBJECT_EMPTY, l.getName()));
				}
				
			}			
		}
			
		LessonClass record=new LessonClass();
		record.setId(id);
		record.setIsUse(isUse);
		this.updateByPrimaryKeySelective(record);
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public List<LessonClass> findLessonClassByUserId(String userId) {
		return lessonClassMapper.findLessonClassByUserId(userId);
	}

	@Override
	public ResBoolSimpleInfo<String> areaDataLimit(String userId,String areaId) {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		List<String> areaIdList=authUserAPI.findUseAreaIdListById(userId);		
		long c=areaIdList.stream().filter(item -> item.equals(areaId)).count();
		if(c==0){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	
}